package sequence

import (
	
	

	
	
	log 
)

const (
	defaultSelfMessageWidth   = 4
	defaultMessageSpacing     = 1
	defaultParticipantSpacing = 5
	boxPaddingLeftRight       = 2
	minBoxWidth               = 3
	boxBorderWidth            = 2
	labelLeftMargin           = 2
	labelBufferSpace          = 10
	frameIndent               = 2 // columns reserved per nested fragment level
	frameLabelInset           = 2 // columns from the left corner to the "[label]" tab
)

func displayWidth( string) int {
	 := 0
	for ,  := range  {
		if  := runeCellWidth();  > 0 {
			 += 
		}
	}
	return 
}

func isDrawingRune( rune) bool {
	return  >= 0x2500 &&  <= 0x257f ||  == '►' ||  == '◄' ||  == '×'
}

func isStructuralRune( rune) bool {
	return isDrawingRune() || strings.ContainsRune("+-|.<>#^v", )
}

// A cell stores all runes rendered at one terminal column. Metadata stays
// separate from cell content so user text cannot be mistaken for renderer state.
type textCell struct {
	content      string
	textual      bool
	continuation bool
}

var continuationCell = textCell{continuation: true}

func cellRune( rune) textCell { return textCell{content: string()} }

func isRuneCell( textCell,  rune) bool {
	return !.textual && !.continuation && .content == string()
}

func textualCell( string) textCell { return textCell{content: , textual: true} }

func isTextualCell( textCell) bool { return .textual && !.continuation }

func appendCellText( textCell,  string) textCell {
	.content += 
	.textual = true
	return 
}

func textCells( string) []textCell {
	 := make([]textCell, 0, displayWidth())
	 := ""
	for ,  := range  {
		 := runeCellWidth()
		if  == 0 {
			 := len() - 1
			for  >= 0 && [].continuation {
				--
			}
			if  >= 0 && isTextualCell([]) {
				[] = appendCellText([], string())
			} else {
				 += string()
			}
			continue
		}

		 :=  != ' ' && !isStructuralRune()
		 := string()
		if  &&  != "" {
			 =  + 
			 = ""
		}
		if  {
			 = append(, textualCell())
		} else {
			 = append(, cellRune())
		}
		for  := 1;  < ; ++ {
			 = append(, continuationCell)
		}
	}
	if  != "" {
		// A zero-width character with no valid base still belongs to the
		// rendered text; retain it in a textual cell rather than dropping it.
		 = append(, textualCell())
	}
	return 
}

func runeCellWidth( rune) int {
	if isDrawingRune() {
		return 1
	}
	return runewidth.RuneWidth()
}

func putText( []textCell,  int,  string) {
	putTextBefore(, , , len())
}

func putTextBefore( []textCell,  int,  string,  int) {
	 := ""
	 := -1
	for ,  := range  {
		 := runeCellWidth()
		if  == 0 {
			if  >= 0 {
				[] = appendCellText([], string())
			} else {
				 += string()
			}
			continue
		}
		if  < 0 || + >  ||  >= len() {
			return
		}
		[] = textualCell( + string())
		 = ""
		 = 
		for  := 1;  <  && + < len(); ++ {
			[+] = continuationCell
		}
		 += 
	}
	if  != "" &&  >= 0 &&  < len() &&  <  && isTextualCell([]) {
		[] = appendCellText([], )
	}
}

func trimCells( []textCell) string {
	 := len()
	for  > 0 && ![-1].textual && ![-1].continuation && [-1].content == " " {
		--
	}
	var  strings.Builder
	for ,  := range [:] {
		if !.continuation {
			.WriteString(.content)
		}
	}
	return .String()
}

type diagramLayout struct {
	participantWidths  []int
	participantCenters []int
	totalWidth         int
	messageSpacing     int
	selfMessageWidth   int
}

func calculateLayout( *SequenceDiagram,  *diagram.Config) *diagramLayout {
	 := .SequenceParticipantSpacing
	if  <= 0 {
		 = defaultParticipantSpacing
	}

	 := make([]int, len(.Participants))
	for ,  := range .Participants {
		 := displayWidth(.Label) + boxPaddingLeftRight
		if  < minBoxWidth {
			 = minBoxWidth
		}
		[] = 
	}

	 := make([]int, len(.Participants))
	 := 0
	for  := range .Participants {
		 := [] + boxBorderWidth
		if  == 0 {
			[] =  / 2
			 = 
		} else {
			 += 
			[] =  + /2
			 += 
		}
	}

	 := len(.Participants) - 1
	 := [] + ([]+boxBorderWidth)/2

	 := .SequenceMessageSpacing
	if  <= 0 {
		 = defaultMessageSpacing
	}
	 := .SequenceSelfMessageWidth
	if  <= 0 {
		 = defaultSelfMessageWidth
	}

	return &diagramLayout{
		participantWidths:  ,
		participantCenters: ,
		totalWidth:         ,
		messageSpacing:     ,
		selfMessageWidth:   ,
	}
}

func ( *SequenceDiagram,  *diagram.Config) (string, error) {
	if  == nil || len(.Participants) == 0 {
		return "", fmt.Errorf("no participants")
	}
	if  == nil {
		 = diagram.DefaultConfig()
	}

	 := Unicode
	if .UseAscii {
		 = ASCII
	}

	 := calculateLayout(, )

	// Fall back to a message-only body for diagrams built without an event
	// stream (e.g. constructed by hand rather than via Parse).
	 := .Events
	if len() == 0 {
		for ,  := range .Messages {
			 = append(, Event{Kind: EventMessage, Message: })
		}
	}

	// Box spacing must know the fragment nesting depth: fragment frames indent
	// per level, and a box border must sit outside the deepest frame that can
	// open around its participants.
	,  := applyBoxSpacing(, , )

	// Nested fragment frames stack their left borders in a gutter to the left of
	// the first participant. A single (unnested) fragment already fits with its
	// border at column 0, so only levels beyond the first need reserved columns;
	// shift the whole diagram right so the borders never overlap the lifelines.
	if  := (fragmentDepth() - 1) * frameIndent;  > 0 {
		shiftLayoutRight(, )
	}

	// A "left of" note on the leftmost participant, or a wide "over" note,
	// extends past column 0. Reserve an additional left gutter so no note box is
	// clamped on top of lifelines it shouldn't cover.
	if  := noteLeftGutter(, );  > 0 {
		shiftLayoutRight(, )
	}

	 := boxSpans(, , , )

	var  []string

	 = append(, buildLine(.Participants, , func( int) string {
		return string(.TopLeft) + strings.Repeat(string(.Horizontal), .participantWidths[]) + string(.TopRight)
	}))

	 = append(, buildLine(.Participants, , func( int) string {
		 := .participantWidths[]
		 := displayWidth(.Participants[].Label)
		 := ( - ) / 2
		return string(.Vertical) + strings.Repeat(" ", ) + .Participants[].Label +
			strings.Repeat(" ", --) + string(.Vertical)
	}))

	 = append(, buildLine(.Participants, , func( int) string {
		 := .participantWidths[]
		return string(.BottomLeft) + strings.Repeat(string(.Horizontal), /2) +
			string(.TeeDown) + strings.Repeat(string(.Horizontal), -/2-1) +
			string(.BottomRight)
	}))

	// act carries the activation state past the body so an activation left open
	// at the end of the diagram still marks the closing lifeline row, the way
	// mermaid runs its activation box to the bottom.
	 := newLifelineState()
	 = append(, renderEvents(, , , )...)

	 = append(, buildLifeline(, , ))

	// Participant-group boxes wrap their columns for the whole diagram height:
	// a titled top border above the headers, side borders overlaid on every
	// body line (crossing arrows and fragment rules become ┼), and a bottom
	// border under the final lifeline row.
	if len() > 0 {
		for ,  := range  {
			[] = overlayBoxSides(, , )
		}
		 = append([]string{boxBorder(, , true)}, ...)
		 = append(, boxBorder(, , false))
	}

	return strings.Join(, "\n") + "\n", nil
}

// boxSpan is a participant group's on-canvas extent: its border columns and
// title. Computed after every layout shift so the columns are final.
type boxSpan struct {
	title       string
	left, right int
}

// applyBoxSpacing widens the layout so each box clears everything drawn
// around its participants: a border column plus padding on both sides (deep
// enough that nested fragment frames stay inside), extra room on the right
// when the title is wider than the participants, and clearance for
// self-message loops and labels on boxed participants. It returns the side
// padding and each box's extra right padding, which boxSpans mirrors.
func applyBoxSpacing( *SequenceDiagram,  *diagramLayout,  []Event) (int, []int) {
	 := make([]int, len(.Boxes))
	if len(.Boxes) == 0 {
		return 0, 
	}

	// Fragment frames indent one step per nesting level; the box border must
	// sit outside the deepest frame so neither erases the other.
	 := 2 + max(0, fragmentDepth()-1)*frameIndent

	 := map[int]int{}
	 := map[int]int{}
	for ,  := range .Boxes {
		[.First] += 

		// The top border must hold: corner, inset, " title ", and at least one
		// horizontal cell before the right corner.
		 := frameLabelInset + displayWidth(.Title) + 4
		 := boxInnerWidth(, ) + 2*
		[] = max(0, -)

		// A self-message on a boxed participant hooks out to the right of its
		// lifeline and carries its label beside it; grow the box so neither
		// pierces the border.
		 := boxRightEdge(, ) + 
		for ,  := range  {
			 := .Message
			if .Kind != EventMessage ||  == nil || .From != .To {
				continue
			}
			if .From.Index < .First || .From.Index > .Last {
				continue
			}
			 := displayWidth(.Label)
			if .Autonumber {
				 += 4 // room for the "NN. " prefix
			}
			 := .participantCenters[.From.Index] +
				max(.selfMessageWidth+1, labelLeftMargin+)
			[] = max([], -+1)
		}

		[.Last] +=  + []
	}

	 := 0
	for  := range .participantCenters {
		 += []
		.participantCenters[] += 
		 += []
	}
	.totalWidth += 
	return , 
}

// boxInnerWidth is the column span of a box's participants before any box
// spacing is applied (calculateLayout coordinates).
func boxInnerWidth( *Box,  *diagramLayout) int {
	return boxRightEdge(, ) - boxLeftEdge(, ) + 1
}

func boxLeftEdge( *Box,  *diagramLayout) int {
	return .participantCenters[.First] - (.participantWidths[.First]+boxBorderWidth)/2
}

func boxRightEdge( *Box,  *diagramLayout) int {
	return .participantCenters[.Last] - (.participantWidths[.Last]+boxBorderWidth)/2 +
		.participantWidths[.Last] + boxBorderWidth - 1
}

// boxSpans resolves each box to its final border columns, mirroring the
// spacing applyBoxSpacing reserved.
func boxSpans( *SequenceDiagram,  *diagramLayout,  int,  []int) []boxSpan {
	 := make([]boxSpan, 0, len(.Boxes))
	for ,  := range .Boxes {
		 = append(, boxSpan{
			title: .Title,
			left:  boxLeftEdge(, ) - ,
			right: boxRightEdge(, ) +  + [],
		})
	}
	return 
}

// boxBorder draws the top (with embedded title) or bottom border row for every
// box on one line.
func boxBorder( []boxSpan,  BoxChars,  bool) string {
	 := 0
	for ,  := range  {
		 = max(, .right+1)
	}
	 := make([]textCell, )
	for  := range  {
		[] = cellRune(' ')
	}
	for ,  := range  {
		,  := .BottomLeft, .BottomRight
		if  {
			,  = .TopLeft, .TopRight
		}
		[.left] = cellRune()
		for  := .left + 1;  < .right; ++ {
			[] = cellRune(.Horizontal)
		}
		[.right] = cellRune()
		if  && .title != "" {
			putTextBefore(, .left+frameLabelInset, " "+.title+" ", .right)
		}
	}
	return trimCells()
}

// overlayBoxSides draws every box's vertical borders onto a body line. A cell
// already carrying a horizontal stroke (a message arrow or fragment rule
// passing through the border) becomes a crossing; any other content (labels,
// note boxes) wins over the border.
func overlayBoxSides( string,  []boxSpan,  BoxChars) string {
	 := 0
	for ,  := range  {
		 = max(, .right+1)
	}
	 := padRunes(, )
	for ,  := range  {
		for ,  := range []int{.left, .right} {
			if isRuneCell([], ' ') {
				[] = cellRune(.Vertical)
			} else if isRuneCell([], .Horizontal) || isRuneCell([], .DottedLine) {
				[] = cellRune(.Cross)
			}
		}
	}
	return trimCells()
}

// renderEvents paints the ordered body of the diagram — messages and fragment
// frames — into text lines. It recurses into each loop/opt block, so nested
// fragments (a loop containing an opt, say) render correctly.
func renderEvents( []Event,  *diagramLayout,  BoxChars,  *lifelineState) []string {
	var  []string
	// emit appends body lines, marking any active lifelines they cross.
	 := func( ...string) {
		for ,  := range  {
			 = append(, .overlay(, , , -1, -1))
		}
	}
	// A note box covers the columns it spans, so junctions are only upgraded
	// outside it: its own borders must survive untouched.
	 := func( *Note) {
		,  := noteBoxColumns(, )
		for ,  := range renderNote(, , , ) {
			 = append(, .overlay(, , , , ))
		}
	}
	for  := 0;  < len(); {
		 := []
		if .Kind == EventFragmentStart {
			 := matchingFragmentEnd(, )
			 = append(, wrapFragment(.Fragment, [+1:], , , )...)
			 =  + 1
			continue
		}

		// Lifeline boundaries draw nothing themselves: they change how the
		// participant's lifeline is drawn from here on.
		if .Kind == EventActivate || .Kind == EventDeactivate ||
			.Kind == EventCreate || .Kind == EventDestroy {
			.apply()
			++
			continue
		}

		// EventFragmentEnd is consumed by matchingFragmentEnd, and top-level
		// EventFragmentDivider is consumed by wrapFragment's section split, so
		// neither should reach here — skip defensively rather than nil-deref on
		// ev.Message below. Log to stderr (never stdout, which carries the
		// diagram) so an unbalanced event stream is diagnosable under -v.
		if .Kind == EventFragmentEnd || .Kind == EventFragmentDivider {
			log.Debugf("renderEvents: unexpected %v at index %d skipped (unbalanced event stream?)", .Kind, )
			++
			continue
		}

		if .Kind == EventNote {
			for  := 0;  < .messageSpacing; ++ {
				(buildLifeline(, , ))
			}
			// The note box covers the lifelines it spans; overlay still marks
			// any active lifeline outside it (it only rewrites lifeline glyphs,
			// so the box itself is untouched).
			(.Note)
			++
			continue
		}

		// EventMessage.
		 := .Message
		for  := 0;  < .messageSpacing; ++ {
			(buildLifeline(, , ))
		}
		if .From == .To {
			(renderSelfMessage(, , , )...)
		} else {
			(renderMessage(, , , )...)
		}
		++
	}
	return 
}

// lifelineState tracks, while the body is rendered, which lifelines are inside
// an activation period and which are not alive yet or already destroyed, so
// each emitted line can be drawn accordingly at those columns.
//
// mermaid draws an activation box beside the lifeline; a heavy lifeline conveys
// the same period without needing columns that ASCII output would have to steal
// from the arrows.
type lifelineState struct {
	depth   map[*Participant]int  // open activation periods
	unborn  map[*Participant]bool // declared by `create`, not reached yet
	dead    map[*Participant]bool // destroyed
	crossed map[*Participant]bool // whose end marker has been drawn
	byIndex []*Participant        // column index -> participant
}

func newLifelineState( *SequenceDiagram) *lifelineState {
	 := &lifelineState{
		depth:   map[*Participant]int{},
		unborn:  map[*Participant]bool{},
		dead:    map[*Participant]bool{},
		crossed: map[*Participant]bool{},
	}
	for ,  := range .Created {
		.unborn[] = true
	}
	.byIndex = .Participants
	return 
}

// glyph is the lifeline cell for the participant in column index i.
func ( *lifelineState) ( int,  BoxChars) rune {
	if  >= len(.byIndex) {
		return .Vertical
	}
	 := .byIndex[]
	switch {
	case .unborn[]:
		return ' '
	case .dead[]:
		if .crossed[] {
			return ' '
		}
		// The first lifeline row after the destroying message marks the end.
		.crossed[] = true
		return .CrossHead
	case .depth[] > 0:
		return .ActiveVertical
	}
	return .Vertical
}

// apply moves the state across a lifeline boundary event.
func ( *lifelineState) ( Event) {
	switch .Kind {
	case EventActivate:
		.depth[.Participant]++
	case EventDeactivate:
		if .depth[.Participant] > 1 {
			.depth[.Participant]--
		} else {
			delete(.depth, .Participant)
		}
	case EventCreate:
		delete(.unborn, .Participant)
	case EventDestroy:
		.dead[.Participant] = true
		delete(.depth, .Participant)
	}
}

// overlay upgrades an already-drawn row's junctions where a message attaches
// to or crosses an active lifeline, so the heavy stroke stays unbroken. It only
// ever rewrites a light junction into its heavy twin at a participant's own
// column, so labels, note boxes and frames are left untouched. Columns in
// [skipFrom, skipTo] are left alone, which note rows use to protect their box.
func ( *lifelineState) ( string,  *diagramLayout,  BoxChars, ,  int) string {
	if len(.depth) == 0 {
		return 
	}
	var  []textCell
	for ,  := range .depth {
		if  == 0 || .dead[] || .unborn[] || .Index >= len(.participantCenters) {
			continue
		}
		 := .participantCenters[.Index]
		if  >=  &&  <=  {
			continue
		}
		if  == nil {
			 = padRunes(, max(.totalWidth+1, displayWidth()))
		}
		if  >= len() {
			continue
		}
		if isRuneCell([], .Vertical) {
			[] = cellRune(.ActiveVertical)
		} else if isRuneCell([], .TeeRight) {
			[] = cellRune(.ActiveTeeRight)
		} else if isRuneCell([], .TeeLeft) {
			[] = cellRune(.ActiveTeeLeft)
		} else if isRuneCell([], .Cross) {
			[] = cellRune(.ActiveCross)
		}
	}
	if  == nil {
		return 
	}
	return trimCells()
}

// fragmentDepth returns the maximum fragment nesting depth within events (0 if
// there are no fragments).
func fragmentDepth( []Event) int {
	,  := 0, 0
	for ,  := range  {
		switch .Kind {
		case EventFragmentStart:
			++
			if  >  {
				 = 
			}
		case EventFragmentEnd:
			--
		}
	}
	return 
}

// matchingFragmentEnd returns the index of the EventFragmentEnd that closes the
// fragment opened at start, accounting for nested fragments.
func matchingFragmentEnd( []Event,  int) int {
	 := 0
	for  := ;  < len(); ++ {
		switch [].Kind {
		case EventFragmentStart:
			++
		case EventFragmentEnd:
			--
			if  == 0 {
				return 
			}
		}
	}
	return len() // unreachable: the parser guarantees balanced fragments
}

// renderNote draws a note annotation as a bordered box positioned over or
// beside its participant lifelines. The box obscures any lifelines it covers,
// while lifelines outside it stay continuous.
// shiftLayoutRight moves every participant (and the total width) right by n
// columns, reserving a left gutter for content that extends past column 0.
func shiftLayoutRight( *diagramLayout,  int) {
	for  := range .participantCenters {
		.participantCenters[] += 
	}
	.totalWidth += 
}

// noteLeftGutter returns how many columns the diagram must shift right so that
// every note box — and the border of each fragment frame enclosing it — fits at
// or right of column 0. A note nested d fragments deep needs room for its box
// plus one border column per enclosing frame plus a one-column margin.
func noteLeftGutter( []Event,  *diagramLayout) int {
	,  := 0, 0
	for ,  := range  {
		switch .Kind {
		case EventFragmentStart:
			++
		case EventFragmentEnd:
			--
		case EventNote:
			,  := noteBoxColumns(.Note, )
			// A top-level note only needs its own box at column 0. A note d
			// frames deep also needs the outermost enclosing border, which sits
			// 1+(d-1)*frameIndent columns to its left (see wrapFragment's stagger).
			 := 0
			if  > 0 {
				 = 1 + (-1)*frameIndent
			}
			if  := - + ;  >  {
				 = 
			}
		}
	}
	return 
}

// noteText returns a note's display text with mermaid line breaks collapsed to
// spaces (ASCII output is single-line).
func noteText( *Note) string {
	 := .Text
	for ,  := range []string{"<br/>", "<br />", "<br>"} {
		 = strings.ReplaceAll(, , " ")
	}
	return 
}

// noteBoxColumns returns the [left, right] columns a note's box occupies. For
// `over`, the box always spans its participants (first..last) and widens
// symmetrically to fit the text; for left/right of it sits beside the lifeline.
// left may be negative when a left-of box extends past column 0 — Render
// reserves a gutter so that never happens at draw time.
func noteBoxColumns( *Note,  *diagramLayout) (int, int) {
	 := displayWidth(noteText()) + 4 // "│ text │"
	 := .participantCenters
	 := [.Participants[0].Index]
	 := [.Participants[len(.Participants)-1].Index]

	switch .Placement {
	case NoteRightOf:
		 :=  + 2
		return ,  +  - 1
	case NoteLeftOf:
		 :=  - 2
		return  -  + 1, 
	default: // NoteOver: span the named participants, widen for text, keep centred
		,  := , 
		if  <  {
			,  = , 
		}
		,  := -1, +1
		if  :=  - ( -  + 1);  > 0 {
			 -=  / 2
			 +=  - /2
		}
		return , 
	}
}

// renderNote draws a note annotation as a bordered box positioned over or
// beside its participant lifelines. The box obscures any lifelines it covers,
// while lifelines outside it stay continuous.
func renderNote( *Note,  *diagramLayout,  BoxChars,  *lifelineState) []string {
	 := noteText()
	,  := noteBoxColumns(, )
	if  < 0 { // safety; Render's note gutter should already prevent this
		 = 0
	}

	 := func(,  rune) string {
		 := padRunes(buildLifeline(, , ), +1)
		[] = cellRune()
		for  :=  + 1;  < ; ++ {
			[] = cellRune(.Horizontal)
		}
		[] = cellRune()
		return trimCells()
	}

	 := padRunes(buildLifeline(, , ), +1)
	for  := ;  <= ; ++ { // clear covered lifelines
		[] = cellRune(' ')
	}
	[] = cellRune(.Vertical)
	[] = cellRune(.Vertical)
	// Centre the text within the box interior [left+1, right-1].
	 :=  -  - 1
	 :=  + 1 + (-displayWidth())/2
	putText(, , )

	return []string{
		(.TopLeft, .TopRight),
		trimCells(),
		(.BottomLeft, .BottomRight),
	}
}

// wrapFragment renders a loop/opt block: it paints the inner body, then draws a
// labelled frame around the participants the block touches.
func wrapFragment( *Fragment,  []Event,  *diagramLayout,  BoxChars,  *lifelineState) []string {
	// An alt block is split into sections by top-level "else" dividers (dividers
	// nested inside child fragments belong to those fragments). Render each
	// section, leaving a placeholder line where each divider will be drawn once
	// the frame width is known.
	,  := splitSections()
	var  []string
	 := map[int]string{}
	for ,  := range  {
		if  > 0 {
			[len()] = [-1]
			 = append(, "") // placeholder for the divider line
		}
		 = append(, renderEvents(, , , )...)
	}
	// A trailing lifeline gives breathing room above the bottom border. It is
	// part of the body, so it carries any activation still open here.
	 = append(, buildLifeline(, , ))

	// The frame spans from just left of the leftmost involved lifeline to just
	// right of the rightmost — the same participants the block's messages touch.
	// Its left border is pushed further left by the depth of frames nested
	// inside it, so each enclosing frame sits outside its children (the gutter
	// reserved in Render guarantees there is room).
	,  := involvedParticipants(, )
	 := .participantCenters[] - frameIndent*(fragmentDepth()+1)
	 := .participantCenters[] + frameIndent

	// A note in the body can extend beyond the participant span (a "left of"
	// note, or one wider than its span). Widen this frame to contain any note
	// box so its border never cuts through it. The margin scales with the note's
	// depth *relative to this frame* (rd) so that when several frames enclose the
	// same note, each outer frame lands frameIndent columns further out than the
	// one inside it (rather than all collapsing onto the note's edge).
	 := 0
	for ,  := range  {
		switch .Kind {
		case EventFragmentStart:
			++
		case EventFragmentEnd:
			--
		case EventNote:
			,  := noteBoxColumns(.Note, )
			if  :=  - 1 - *frameIndent;  <  {
				 = 
			}
			if  :=  + 1 + *frameIndent;  >  {
				 = 
			}
		}
	}
	if  < 0 {
		 = 0
	}

	// Message labels can extend well past the rightmost lifeline, so widen the
	// frame to clear the longest inner line.
	for ,  := range  {
		if  := displayWidth() + 1;  >  {
			 = 
		}
	}

	 := .Type.String()
	if .Label != "" {
		 += " " + .Label
	}

	// The label tab ("[label]") sits frameLabelInset cells in from the left
	// corner; make sure the frame is wide enough to hold it (and every "else"
	// divider label) without truncation.
	 := func( string) {
		if  :=  + frameLabelInset + displayWidth("["++"]") + 1;  >  {
			 = 
		}
	}
	()
	for ,  := range  {
		if  != "" {
			()
		}
	}

	 := []string{fragmentBorder(, , , , , true, )}
	for ,  := range  {
		if ,  := [];  {
			 = append(, fragmentDivider(, , , , , ))
		} else {
			 = append(, overlayFrameSides(, , , ))
		}
	}
	 = append(, fragmentBorder(, , , , "", false, ))
	return 
}

// splitSections divides a fragment body at its top-level "else" dividers,
// returning the section event-slices and the label of the divider preceding
// each section after the first. Dividers nested inside child fragments are left
// in place (they belong to those fragments).
func splitSections( []Event) ([][]Event, []string) {
	var  [][]Event
	var  []string
	 := []Event{}
	 := 0
	for ,  := range  {
		switch .Kind {
		case EventFragmentStart:
			++
		case EventFragmentEnd:
			--
		case EventFragmentDivider:
			if  == 0 {
				 = append(, )
				 = append(, .Fragment.Label)
				 = []Event{}
				continue
			}
		}
		 = append(, )
	}
	return append(, ), 
}

// fragmentDivider draws an alt "else" divider: a dashed line spanning the frame
// and joined to its side borders, with an optional [label] tab near the left.
func fragmentDivider( *diagramLayout,  BoxChars, ,  int,  string,  *lifelineState) string {
	 := padRunes(buildLifeline(, , ), +1)
	[] = cellRune(.TeeRight)
	for  :=  + 1;  < ; ++ {
		[] = cellRune(.DottedLine)
	}
	[] = cellRune(.TeeLeft)
	if  != "" {
		putTextBefore(, +frameLabelInset, "["++"]", )
	}
	return trimCells()
}

// involvedParticipants returns the smallest and largest participant indices
// referenced by the messages in events. If there are no messages it falls back
// to spanning every participant.
func involvedParticipants( []Event,  *diagramLayout) (int, int) {
	,  := -1, -1
	 := func( int) {
		if  == -1 ||  <  {
			 = 
		}
		if  == -1 ||  >  {
			 = 
		}
	}
	for ,  := range  {
		if .Kind == EventMessage {
			(.Message.From.Index)
			(.Message.To.Index)
		}
	}
	if  == -1 {
		return 0, len(.participantCenters) - 1
	}
	return , 
}

// fragmentBorder builds a top or bottom frame border on top of a lifeline row,
// so participant lines outside the frame stay continuous. When top is true and
// label is non-empty, the label is embedded as a "[label]" tab near the left
// corner.
func fragmentBorder( *diagramLayout,  BoxChars, ,  int,  string,  bool,  *lifelineState) string {
	 := padRunes(buildLifeline(, , ), +1)

	,  := .BottomLeft, .BottomRight
	if  {
		,  = .TopLeft, .TopRight
	}
	[] = cellRune()
	for  :=  + 1;  < ; ++ {
		[] = cellRune(.Horizontal)
	}
	[] = cellRune()

	if  != "" {
		putTextBefore(, +frameLabelInset, "["++"]", )
	}
	return trimCells()
}

// overlayFrameSides draws the left and right vertical borders of a frame onto an
// already-rendered content line.
func overlayFrameSides( string,  BoxChars, ,  int) string {
	 := padRunes(, +1)
	[] = cellRune(.Vertical)
	[] = cellRune(.Vertical)
	return trimCells()
}

// padRunes returns s as a cell-indexed slice right-padded with spaces to at least width.
func padRunes( string,  int) []textCell {
	 := textCells()
	for len() <  {
		 = append(, cellRune(' '))
	}
	return 
}

func buildLine( []*Participant,  *diagramLayout,  func(int) string) string {
	var  strings.Builder
	for  := range  {
		 := .participantWidths[] + boxBorderWidth
		 := .participantCenters[] - /2

		 :=  - displayWidth(.String())
		if  > 0 {
			.WriteString(strings.Repeat(" ", ))
		}
		.WriteString(())
	}
	return trimCells(textCells(.String()))
}

// buildLifeline draws the bare lifeline row. st, when non-nil, decides each
// participant's cell: blank before it is created or after it is destroyed, the
// end marker on the first row after destruction, and the heavy stroke while it
// is active. Drawing this here (rather than patching a finished row) means
// message labels and note boxes painted afterwards are never disturbed.
func buildLifeline( *diagramLayout,  BoxChars,  *lifelineState) string {
	 := make([]textCell, .totalWidth+1)
	for  := range  {
		[] = cellRune(' ')
	}
	for ,  := range .participantCenters {
		if  >= len() {
			continue
		}
		[] = cellRune(.Vertical)
		if  != nil {
			[] = cellRune(.glyph(, ))
		}
	}
	return trimCells()
}

func renderMessage( *Message,  *diagramLayout,  BoxChars,  *lifelineState) []string {
	var  []string
	,  := .participantCenters[.From.Index], .participantCenters[.To.Index]

	 := .Label
	if .Number > 0 {
		 = fmt.Sprintf("%d. %s", .Number, .Label)
	}

	if  != "" {
		 := min(, ) + labelLeftMargin
		 := displayWidth()
		 := max(.totalWidth, +) + labelBufferSpace
		 := padRunes(buildLifeline(, , ), )

		putText(, , )
		 = append(, trimCells())
	}

	 := padRunes(buildLifeline(, , ), .totalWidth+1)
	 := cellRune(.SolidLine)
	if .ArrowType.isDotted() {
		 = cellRune(.DottedLine)
	}

	if  <  {
		[] = cellRune(.TeeRight)
		for  :=  + 1;  < ; ++ {
			[] = 
		}
		// Open arrows (-> / -->) have no head: draw the line right up to the
		// target lifeline instead of an arrowhead.
		if ,  := .ArrowType.head(, true);  {
			[-1] = cellRune()
		}
		// Bidirectional arrows carry a head at the source end too. This can
		// never clobber the target head: participant centers are always ≥6
		// columns apart (box width ≥5 plus spacing ≥1), so from+1 < to-1.
		if .ArrowType.isBidirectional() {
			[+1] = cellRune(.ArrowLeft)
		}
		[] = cellRune(.Vertical)
	} else {
		[] = cellRune(.Vertical)
		[+1] = 
		if ,  := .ArrowType.head(, false);  {
			[+1] = cellRune()
		}
		for  :=  + 2;  < ; ++ {
			[] = 
		}
		if .ArrowType.isBidirectional() {
			[-1] = cellRune(.ArrowRight)
		}
		[] = cellRune(.TeeLeft)
	}
	// Central connections replace the lifeline attachment with a circle.
	if .CentralFrom {
		[] = cellRune(.Circle)
	}
	if .CentralTo {
		[] = cellRune(.Circle)
	}
	 = append(, trimCells())
	return 
}

func renderSelfMessage( *Message,  *diagramLayout,  BoxChars,  *lifelineState) []string {
	var  []string
	 := .participantCenters[.From.Index]
	 := .selfMessageWidth

	 := func( string) []textCell {
		return padRunes(, .totalWidth++1)
	}

	 := .Label
	if .Number > 0 {
		 = fmt.Sprintf("%d. %s", .Number, .Label)
	}

	if  != "" {
		 :=  + labelLeftMargin
		 := displayWidth()
		 :=  +  + labelBufferSpace
		 := padRunes(buildLifeline(, , ), )
		putText(, , )
		 = append(, trimCells())
	}

	// Solid arrows keep the solid horizontal glyph; dotted arrows (-->>/-->) use
	// the dotted line. For solid arrows style == chars.Horizontal, so output is
	// unchanged from before.
	 := cellRune(.Horizontal)
	if .ArrowType.isDotted() {
		 = cellRune(.DottedLine)
	}

	 := (buildLifeline(, , ))
	[] = cellRune(.TeeRight)
	if .CentralFrom {
		[] = cellRune(.Circle)
	}
	for  := 1;  < ; ++ {
		[+] = 
	}
	[+-1] = cellRune(.SelfTopRight)
	 = append(, trimCells())

	 := (buildLifeline(, , ))
	[+-1] = cellRune(.Vertical)
	 = append(, trimCells())

	 := (buildLifeline(, , ))
	[] = cellRune(.Vertical)
	if .CentralTo {
		[] = cellRune(.Circle)
	}
	// Open arrows have no head. A bidirectional self-message collapses to a
	// single head: both of its ends sit on the same lifeline, and the return
	// head is where they coincide.
	[+1] = 
	if ,  := .ArrowType.head(, false);  {
		[+1] = cellRune()
	}
	for  := 2;  < -1; ++ {
		[+] = 
	}
	[+-1] = cellRune(.SelfBottom)
	 = append(, trimCells())

	return 
}